<?php

namespace Home\Controller;

use Home\Biz\DealerBiz;
use Think\Controller;

use Home\Biz\CommonBiz;
use Home\Biz\OrderBiz;

class OrderController extends LoginBaseController {
	

	public function orderinfo() {
		
		$this->display('order/orderinfo');
		
	}
	
	public function dealerOrderInfo() {
		$this->display('dealer/dealerOrderInfo');
	}
	
	
	public function home() {
	
		$this->display('home/home');
	
	}
	
	public function orderdetail(){
		$order_id = I('order_id');
		
		
		$order_info_en = M('order_info')->where(array('order_id'=>$order_id))->find();
		
		$lst_order_detail_en = M('order_detail')->where(array('order_id'=>$order_id))->select();
		
		$lst_order_discount_en = M('order_discount')->where("order_id='%s' and discount_type not in ('1','99')", $order_id)->select();
		
		$order_payment_en = M('order_payment')->where(array('order_id'=>$order_id))->find();
		
		$order_info_en['order_status_text'] = CommonBiz::changeWhaleyOrderStatus($order_info_en['order_status']);
		
		$order_info_en['invoice_kind_text'] = CommonBiz::changeInvoiceKind($order_info_en['invoice_kind']);
		
		$order_info_en['order_type_text']	= CommonBiz::changeOrderType($order_info_en['order_type']);
		
		
		
		$order_info_en['total_address'] = $order_info_en['consignee_province'].$order_info_en['consignee_city'].$order_info_en['consignee_district'].'  '.$order_info_en['consignee_address'];
		
		$order_info_en['point_amount'] =$order_payment_en['point_amount'];
		
		if($order_info_en['point_amount']==null){
			$order_info_en['point_amount'] ='0.00';
		}
		
		if(empty($order_info_en['invoice_title'])){
			$order_info_en['invoice_title'] = $order_info_en['invoice_name'];
		}
		$lst_order_server_en = M('order_server_detail')->where(array('order_id'=>$order_id))->select();
		
		//查询物流信息 去重物流编号
		if(count($lst_order_detail_en) >= 1){
			//将有效运单号保存去重后进行查询
			$logistics_nos = array();
			foreach($lst_order_detail_en as $row){
				if(!empty($row['logistics_no'])){
					array_push($logistics_nos,$row['logistics_no']);
				}
			}
			if(count($logistics_nos) >= 1){
				$logistics_log_param['logistics_no']  = array('in',array_unique ( $logistics_nos ));
				$logistics_log_param['delete']  = 1;
				
			 	$lst_logistics_log = 
			 		M('logistics_log')->where($logistics_log_param)->order('logistics_no,logistics_date,logistics_time') -> select();
	 			$this->assign('lst_logistics_log',$lst_logistics_log);
			}
		}
		$this->assign('order_info_en', $order_info_en);
		$this->assign('lst_order_discount_en',$lst_order_discount_en);
		$this->assign('lst_order_detail_en',$lst_order_detail_en);
		$this->assign('lst_order_server_en',$lst_order_server_en);
		$this->display('order/orderdetail');
	}
	
	/**
	 * 上传订单折扣数据
	 */
	public function orderDiscountUpload(){
		
		$this->display('order/uploadOrderDiscount');
	}

	/**
	 * 上传订单折扣数据结果页
	 */
	public function uploadOrderDiscountResult(){
		
		$this->assign('msg', I('msg'));
		$this->display('order/uploadOrderDiscountResult');
	}
	
	public function orderexport(){
		$thirdOrderId =I('thirdOrderId');
		$message = I('message');
		$orderId = I('orderId');
		$reveiverAdd = I('reveiverAdd');
		$orderStatus = I('orderStatus');
		$orderEndDate = I('orderEndDate');
		$orderStartDate = I('orderStartDate');
		$cashBackStatus = I('cashBackStatus');
		$invoiceKind = I('invoiceKind');
		$invoiceStatus = I('invoiceStatus');
		$consigneeName = I('consigneeName');
		$receiverMobile = I('receiverMobile');
		$orderType = I('orderType');
		$invoiceDate = I('invoiceDate');
    	$orderEndTime = I('orderEndTime');
    	$orderEndTimeEnd = I('orderEndTimeEnd');
    	 
		$con = array();
		
		if(!empty($thirdOrderId)){
			array_push($con, "third_order_id like '%$thirdOrderId%'");
		}
		
		if(!empty($receiverMobile)){
			array_push($con, "consignee_cellphone = '$receiverMobile'");
		}
		
		if(!empty($consigneeName)){
			array_push($con, "consignee_name = '$consigneeName'");
		}
		
		if(!empty($message)){
		
			if(	$message=='true'){
				array_push($con, "(buyer_message is not null or seller_memo is not null) ");
			}
		}
		
		if(!empty($orderId)){
			array_push($con, "order_id like '%$orderId%'");
		}
		
		if(!empty($orderType)){
			array_push($con, "order_type = '$orderType'");
		}
		
		if(!empty($reveiverAdd)){
			array_push($con, "consignee_address like '%$reveiverAdd%'");
		}
		
		if (! empty ( $invoiceDate )) {
			array_push($con, "date(invoice_date) = '$invoiceDate'");
		}
		
		if (! empty ( $orderEndTime )) {
			array_push($con, "date(order_end_time) >= '$orderEndTime'");
		}
		
		if (! empty ( $orderEndTimeEnd )) {
			array_push($con, "date(order_end_time) <= '$orderEndTimeEnd'");
		}
		
		if(!empty($orderStatus)){
			array_push($con, "order_status ='$orderStatus'");
		}
		
		if(!empty($orderStartDate)){
			array_push($con, "date(order_date) >= '$orderStartDate'");
		}
		
		if(!empty($orderEndDate)){
			array_push($con, "date(order_date) <= '$orderEndDate'");
		}
		
		if(!empty($cashBackStatus)){
			array_push($con, "cash_back_status = '$cashBackStatus'");
		}
		
		if(!empty($invoiceKind)){
			array_push($con, "invoice_kind = '$invoiceKind'");
		}
		
		if(!empty($invoiceStatus)){
			array_push($con, "invoice_status = '$invoiceStatus'");
		}
		
		
		ini_set("max_execution_time", "0");
	
		
		$list_order_infos = M ( 'order_info' )->field("`order_id`,`third_order_id`,`consignee_cellphone`,`invoice_name`,`invoice_title`,`consignee_zip`
       		,`buyer_nick`, `invoice_kind`, `consignee_name`,`consignee_province`,`consignee_city`,`consignee_district`,`consignee_address`,`invoice_address` ,`order_date` ")
		       		->where (join(" AND ",$con) )->select ();
		
		       		Vendor('phpExcel.PHPExcel');
		       		$excel = new  \PHPExcel();
		       		$settings = new \PHPExcel_CachedObjectStorageFactory();
		       		$settings::cache_to_discISAM;
		       		
		       		$data = array();
		       		
		       		if($invoiceKind=='22'||$invoiceKind=='23'){
		       			
		       			$letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W');
		       			//表头数组
		       			$tableheader = array('订单号',
		       					'发票抬头',
		       					'税号',
		       					'地址电话',
		       					'银行账号',
		       					'商品名称',
		       					'规格型号',
		       					'商品单位',
		       					'商品数量',
		       					'商品金额',
		       					'税率',
		       					'折扣金额',
		       					'快递单号',
		       					'收件人姓名',
		       					'收件人手机',
		       					'收件人地址',
		       					'邮编'
		       			);
		       			//填充表头信息
		       			for($i = 0;$i < count($tableheader);$i++) {
		       				$excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
		       			}
		       			
		       			$lst_HasServerPackSkUId = explode(',', C('InvoiceConfig.HasServerPackSkUIdList'));
		       			
		       			//获取VIP会员服务并映射成K-V格式
		       			$vip_bag_lst = OrderBiz::getVipBagLst();
		       			foreach($list_order_infos as $order_info_en){
		       				$address = $order_info_en['invoice_address'];//发票邮寄地址
		       				if(empty($address)){
		       					$address = $order_info_en['consignee_province'].$order_info_en['consignee_city'].$order_info_en['consignee_district'].'  '.$order_info_en['consignee_address'];
		       				}
		       				$orderId = $order_info_en['order_id'];
		       				$id= $order_info_en['third_order_id'];
		       				if(empty($id)){
		       					$id = $orderId;
		       				}
		       				$lst_order_detail = M('order_detail')->field(`third_sku_id`,`third_order_id`,`qty`,`payment_amount`)->where("order_id='$orderId'")->select();
		       				if(sizeof($lst_order_detail) > 0){
			       				//查询付款信息并计算发票总金额
			       				$payment_info = OrderBiz::getCaculatePaymentInfo($orderId);
			       				//查询订单总金额
			       				$sum_payment_amount = M('order_detail')->where("order_id ='%s'", $orderId)->sum('payment_amount');
			       				//折扣金额 = 总额 - 发票金额
			       				$discount_amounts = ($sum_payment_amount - $payment_info['invoice_amount']);
			       				
			       				$invoiceTitle = $order_info_en['invoice_name'];
								//发票抬头		       				
			       				if(!empty($order_info_en['invoice_title'])){
			       					$invoiceTitle = $order_info_en['invoice_title'];
			       				}
			       				
			       				$common_info = array(
			       					'id' => ' '.$id,
			       					'title' => $invoiceTitle,
			       					'address' => $address,
			       					'consignee_name' => $order_info_en['consignee_name'],//收件人姓名
				       				'consignee_cellphone' => ' '.$order_info_en['consignee_cellphone'],//收件人手机
				       				'consignee_zip' => $order_info_en['consignee_zip']//邮编
			       				);
			       				//获取产品配置并映射成K-V格式
			       				$lst_prd_split = OrderBiz::getProductSplitBySkuIds($lst_order_detail, 'third_sku_id');
			       				foreach ($lst_order_detail as $order_detail_en){
			       					//是否在配置信息中存在数据
			       					if($lst_prd_split[$order_detail_en['third_sku_id']] != null){
			       						//获取配置列拆分后的数组
			       						$prd_split_info = $lst_prd_split[$order_detail_en['third_sku_id']];
			       						//支付金额大于0的情况构造发票信息
			       						if($order_detail_en['payment_amount'] > 0){
				       						//会员包价格 根据配置信息判断该产品有没有配置会员包 若配置取出相应会员包的售价
				       						$vip_bag_info = $vip_bag_lst[$prd_split_info['referent_id']];
				       						//取出会员包的含税价格 便于下一步计算
				       						$vipBagAmount = floatval( empty($vip_bag_info) ? 0 : $vip_bag_info['sale_amount'] );
				       						$vipBagPrice = floatval($vipBagAmount) *  $order_detail_en['qty'];
				       						$tv_amount = $order_detail_en['payment_amount'] -$vipBagPrice;
				       						$qty = $order_detail_en['qty'];
				       						//构造商品发票明细
				       						$itemstv = OrderBiz::paperInvItm4Export($common_info, $qty, $tv_amount, $discount_amounts, $prd_split_info);
				       						array_push($data,$itemstv);
				       						//存在会员包信息或者会员包价格大于0 需要包装会员包明细数据
				       						if($vipBagAmount > 0){
				       							//构造会员服务发票明细
				       							$itemsvipBag = OrderBiz::paperInvItm4Export($common_info, $qty, $vipBagPrice, '', $vip_bag_info);
					       						array_push($data,$itemsvipBag);
				       						}
			       						}
			       					}else{
			       						array_push($data,OrderBiz::paperInvItm4Export($common_info, 0, 0, '', array('invoice_title' => '该商品SKU信息未配置,请联系管理员')));
			       					}
			       				}
			       				
			       				M('order_info')->execute("update order_info set  invoice_status = 15
			       						where order_id ='$orderId'");
		       				}
		       			}
		       			
		       			
		       		}else{
		       		//Excel表格式,这里简略写了8列
		       		$letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W');
		       		//表头数组
		       		$tableheader = array('发票类型',
		       				'销售订单号',
		       				'发票号码',
		       				'快递单号',
		       				'开票日期',
		       				'客户名称',
		       				'发票名称',
		       				'型号',
		       				'计量单位',
		       				'产品数量',
		       				'单价',
		       				'金额',
		       				'税额',
		       				'价税合计',
		       				'含税单价',
		       				'税率',
		       				'收货人',
		       				'联系方式',
		       				'地址'
		       		);
		       		//填充表头信息
		       		for($i = 0;$i < count($tableheader);$i++) {
		       			$excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
		       		}
		       		
		       		foreach($list_order_infos as $order_info_en){
		       			$thirdOrderId=$order_info_en['third_order_id'];
		       			$orderId=$order_info_en['order_id'];
		       			$order_invoice_en = M('order_invoice')->field(`invoice_no`,`invoice_date`,`invoice_name`)->where("order_id='$orderId' and status=1")->find();
		       				
		       			$serials_no = $order_invoice_en['invoice_serial_no'];
		       			$lst_order_invoice_en_item = M('order_invoice_item')->where("invoice_serial_no='$serials_no'")->select();
		
		       			foreach ($lst_order_invoice_en_item as $order_invoice_item){
		       				$items = array(
		
		       						CommonBiz::changeInvoiceKind($order_info_en['invoice_kind']),
		       						' '.$order_info_en['third_order_id'],
		       						' '.$order_invoice_en['invoice_no'],
		       						'',$order_invoice_en['invoice_date'],
		       						$order_invoice_en['invoice_name'],
		       						$order_invoice_item['item_name'],
		       						$order_invoice_item['specification'],
		       						$order_invoice_item['unit'],
		       						$order_invoice_item['quantity'],
		       						$order_invoice_item['price'],
		       						$order_invoice_item['sum_price'],
		       						$order_invoice_item['tax'],
		       						$order_invoice_item['invoice_amount'],
		       						'',$order_invoice_item['tax_rate'],
		       						$order_info_en['consignee_name'],
		       						' '.$order_info_en['consignee_cellphone'],
		       						$order_info_en['consignee_province'].$order_info_en['consignee_city'].$order_info_en['consignee_district'].'  '.$order_info_en['consignee_address']
		
		       				);
		       				array_push($data,$items);
		       			}
		
		       		}
		       		
		       		}
		       				
		       		 
		       		for ($i = 2;$i <= count($data) + 1;$i++) {
		       			$j = 0;
		       			foreach ($data[$i - 2] as $key=>$value) {
		       				$excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
		       				$j++;
		       			}
		       		}
		
		       		$write = new \PHPExcel_Writer_Excel5($excel);
		       		ini_set("max_execution_time", "0");
		       		header("Pragma: public");
		       		header("Expires: 0");
		       		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
		       		header("Content-Type:application/force-download");
		       		header("Content-Type:application/vnd.ms-execl");
		       		header("Content-Type:application/octet-stream");
		       		header("Content-Type:application/download");;
		       		header('Content-Disposition:attachment;filename="导出订单.xls"');
		       		header("Content-Transfer-Encoding:binary");
		       		$write->save('php://output');
		
	}
	
	
	public function orderInfoexportExcel(){
		$thirdOrderId =I('thirdOrderId');
		$message = I('message');
		$orderId = I('orderId');
		$reveiverAdd = I('reveiverAdd');
		$orderStatus = I('orderStatus');
		$orderEndDate = I('orderEndDate');
		$orderStartDate = I('orderStartDate');
		$cashBackStatus = I('cashBackStatus');
		$invoiceKind = I('invoiceKind');
		$invoiceStatus = I('invoiceStatus');
		$consigneeName = I('consigneeName');
		$receiverMobile = I('receiverMobile');
		$orderType = I('orderType');
		$invoiceDate = I('invoiceDate');
		$orderEndTime = I('orderEndTime');
		$orderEndTimeEnd = I('orderEndTimeEnd');
		
		$con = array();
		if(!empty($thirdOrderId)){
			array_push($con, "o.third_order_id like '%$thirdOrderId%'");
		}
	
		if(!empty($receiverMobile)){
			array_push($con, "o.consignee_cellphone = '$receiverMobile'");
		}
	
		if(!empty($consigneeName)){
			array_push($con, "o.consignee_name = '$consigneeName'");
		}
	
		if(!empty($message)){
			if(	$message=='true'){
				array_push($con, "(o.buyer_message is not null or o.seller_memo is not null) ");
			}
		}
	
		if(!empty($orderId)){
			array_push($con, "o.order_id like '%$orderId%'");
		}
	
		if(!empty($orderType)){
			array_push($con, "o.order_type = '$orderType'");
		}
	
		if(!empty($reveiverAdd)){
			array_push($con, "o.consignee_address like '%$reveiverAdd%'");
		}
	
		if(!empty($orderStatus)){
			array_push($con, "o.order_status ='$orderStatus'");
		}
	
		if(!empty($orderStartDate)){
			array_push($con, "date(o.order_date) >= '$orderStartDate'");
		}
	
		if(!empty($orderEndDate)){
			array_push($con, "date(o.order_date) <= '$orderEndDate'");
		}
		
		if (! empty ( $orderEndTime )) {
			array_push($con, "date(o.order_end_time) >= '$orderEndTime'");
		}
		
		if (! empty ( $orderEndTimeEnd )) {
			array_push($con, "date(o.order_end_time) <= '$orderEndTimeEnd'");
		}
		
		if (! empty ( $invoiceDate )) {
			array_push($con, "date(o.invoice_date) = '$invoiceDate'");
		}
	
		if(!empty($cashBackStatus)){
			array_push($con, "o.cash_back_status = '$cashBackStatus'");
		}
	
		if(!empty($invoiceKind)){
			array_push($con, "o.invoice_kind = '$invoiceKind'");
		}
	
		if(!empty($invoiceStatus)){
			array_push($con, "o.invoice_status = '$invoiceStatus'");
		}
		Vendor('phpExcel.PHPExcel');
		$objPHPExcel = OrderBiz::OrderExportExcel($con);
		//输出到浏览器
		$objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
		header("Content-Type:application/force-download");
		header("Content-Type:application/vnd.ms-execl");
		header("Content-Type:application/octet-stream");
		header("Content-Type:application/download");
		header('Content-Disposition:attachment;filename="orderInfo.xls"');
		header("Content-Transfer-Encoding:binary");
		$objWriter->save('php://output');
	}
	
	public function orderDiscountUploadAction(){
		
		$upload_config = array(
				'maxSize'	=> 0,
				'rootPath'	=> './Public/Uploads/',
				'savePath'	=> 'order_discount/',
				'saveName'	=> 'order_discount',
				'exts'		=> array('csv'),
				'subName' => '',
				'replace' => true,
		);

		
		ini_set('max_execution_time', '0');
		$upload = new \Think\Upload($upload_config); // 实例化上传类
        $upload->autoSub = false;

		$info = $upload->upload();
		if (!$info) { 
			// 上传错误提示错误信息
			redirect('uploadOrderDiscountResult?msg=上传失败！'.$upload->getError());
		} else { 
			// 上传成功
			//读取csv文件将相关数据写入数据库
			$csv_file = fopen('./Public/Uploads/order_discount/order_discount.csv','r');
			while($row_data = fgetcsv($csv_file)) {
				$tid = $row_data[0];
				$amount = $row_data[2];
				$before_amount = $row_data[1];
				$order_info_en = M('orderInfo')->where("third_order_id='$tid'")->find();
				//存在order_info
				if(!empty($order_info_en)){

					//不存在同类型折扣
					if($order_info_en['cash_back_status']==0){
						
						$third_order_id = $order_info_en['third_order_id'];
						// 写入order_discount表
						$order_discount_add_en = array(
								'order_id'	=> $order_info_en['order_id'],
								'third_order_id'	=> $third_order_id,
								'discount_type'		=> 3,
								'discount_name'		=> 'o2o云推广天猫返现',
								'discount_amount'	=> $amount,
								'discount_desc'		=> 'o2o云推广天猫返现(后返)'.strval($amount),
								'promotion_id'		=> 'WJFX_TM_'.$order_info_en['third_order_id'],
								'create_user'		=> 'whaleyinfo.order.order orderDiscountUploadAction',
								'create_date'		=> date("y-m-d H:i:s", time()),
						);
						M('orderDiscount')->add($order_discount_add_en);
						
						$order_discount_before = array(
								'order_id'	=> $order_info_en['order_id'],
								'third_order_id'	=> $third_order_id,
								'discount_type'		=> 7,
								'discount_name'		=> 'o2o云推广天猫返现',
								'discount_amount'	=> $before_amount,
								'discount_desc'		=> 'o2o云推广天猫返现(前返)'.strval($before_amount),
								'promotion_id'		=> 'WJFX_QF_TM_'.$order_info_en['third_order_id'],
								'create_user'		=> 'whaleyinfo.order.order orderDiscountUploadAction',
								'create_date'		=> date("y-m-d H:i:s", time()),
						);
						M('orderDiscount')->add($order_discount_before);
						
						// 更新orderPayment表的cashback_amount金额
						M('orderPayment')
							->where("third_order_id='$third_order_id'")
							->setField('cashback_amount', $amount);
						
					    //将orderInfo表中的cash_back_status修改成1 已经上传 
						M('orderInfo')->where("third_order_id='$third_order_id'")
						->setField('cash_back_status',1);
					}
				}
			}
			
			
			redirect('uploadOrderDiscountResult?msg=已成功上传并处理！');
		}
		
		
		
	}
	
	public  function orderCancelConfirm(){
		
			
		$order_id = I('order_id');
		$order_en = M('order_info')->where("order_id ='%s'",$order_id)->find();
		
		if(empty($order_en)){
			$error_msg="订单不存在!";
			redirect(C('AdminConfig.error_info_page').'?type=202&msg=失败,'.$error_msg);
			return;		
		}else{
			
			$this->assign("order_id",$order_id);
			$this->display("order/confirmordercancel");
			return;			
		}
			
	}	
	
	
	public  function orderCancel(){
		$order_id = I('order_id');
		$cancel_reason = I('cancel_reason');
		$remark = I('remark');
		$order_en = M('order_info')->where("order_id ='%s'",$order_id)->find();
	    
		if(empty($order_en)){
			$error_msg="订单不存在!";
			redirect(C('AdminConfig.error_info_page').'?type=202&is_show_button=2&msg=失败,'.$error_msg);
			return;
		}else{
			
			$order_type  = $order_en['order_type'];
			$order_status = $order_en['order_status'];

			
			
			if($order_status ==51 || $order_status== 52 || $order_status==53 || $order_status==54){
				$error_msg="订单状态非法,该订单已经被取消!";
				redirect(C('AdminConfig.error_info_page').'?type=202&is_show_button=2&msg=失败,'.$error_msg);
				return;
			}
			
			if($order_en['rma_qty'] > 0){
				$error_msg="订单已有退换货，禁止取消!";
				redirect(C('AdminConfig.error_info_page').'?type=202&is_show_button=2&msg=失败,'.$error_msg);
				return;
			}
			
			
			$order_cancel = array(
					"order_id" => $order_id,
					"role_type" =>2,//客服取消
					"role_user_id" => cookie('login_user_id'),
					"cancel_reason" => $cancel_reason,
					"remark" => $remark,
					"create_user" =>'whaleyinfo.order order.orderCancel',
					"create_date" =>date("y-m-d H:i:s", time()),
					
			);
			$order_change_log = array(
					"order_id" => $order_id,
					"order_status" =>52,
					"order_status_text" =>'客服已取消',
					"create_user" =>'whaleyinfo.order order.orderCancel',
					"create_date" =>date("y-m-d H:i:s", time()),
			);
			
			//更新order_info 表，设置订单状态为52，客服取消
			M('order_info')->where("order_id ='%s'",$order_id)->setField("order_status",52);
			M('order_cancel')->data($order_cancel)->add();
			M('order_status_change_log')->data($order_change_log)->add();


            //判断订单是否经销商渠道和余额支付，若是，并已支付，则需要将余额退回
            if($order_en['order_type'] == 8 && $order_en['payment_type'] == 3 && $order_en['payment_status'] == 1){

                //退回余额到账户
                $order_payment_en   = M('order_payment')->where("order_id ='%s'",$order_id)->find();
                $dealer_id          = $order_payment_en['account_id'];
                $dealer_en          = M('dealer_info')->where("dealer_id ='%s'", $dealer_id)->find();


                //region ============= 1、变更余额 begin =============
                $dealer_new_amount = $dealer_en['amount'] + $order_payment_en['account_amount'];
                M('dealer_info')
                    ->where("dealer_id='%s'", $dealer_id)
                    ->setField('amount', $dealer_new_amount);
                //插入经销商余额表
                $dealer_amount = array(
                    "dealer_amount_id"	=> DealerBiz::generateDealerAmountId(),
                    "dealer_id"   =>$dealer_en['dealer_id'],
                    "dealer_name" =>$dealer_en['dealer_name'],
                    "amount_kind" =>1,//减少
                    "amount_type" =>15,//订单取消余额退回
                    "amount"      =>$order_payment_en['account_amount'],//订单金额
                    "begin_amount"=>$dealer_en['amount'],
                    "end_amount"  =>$dealer_new_amount,
                    "order_id"    =>$order_id,
                    "remark" =>"订单取消余额退回",
                    "status" =>1,//有效
                    'create_user' => "whaleyinfo.order DealerBiz.submitDealerOrder",
                    'create_date' => date ( "y-m-d H:i:s", time () )
                );
                M('dealer_amount')->add($dealer_amount);
                //endregion ============= 1、变更余额 End =============


                //region ============= 2、变更返现余额 begin =============
                if($order_en['payment_method'] == 31){
	                $dealer_cashback_amount = $order_payment_en['cashback_account_amount'];
	                if($dealer_cashback_amount > 0){
	                    $dealer_new_cashback_amount = $dealer_en['cashback_amount'] + $dealer_cashback_amount;
	                    M('dealer_info')
	                        ->where("dealer_id='%s'", $dealer_id)
	                        ->setField('cashback_amount', $dealer_new_cashback_amount);
	                    $dealer_cashback_amount = array(
	                        "dealer_amount_id"	=> DealerBiz::generateDealerAmountId(),
	                        "dealer_id"   =>$dealer_en['dealer_id'],
	                        "dealer_name" =>$dealer_en['dealer_name'],
	                        "amount_kind" =>1,//增加
	                        "amount_type" =>15,//订单取消余额退回
	                        "amount"      =>$dealer_cashback_amount,
	                        "begin_amount"=>$dealer_en['cashback_amount'],
	                        "end_amount"  =>$dealer_new_cashback_amount,
	                        "order_id"    =>$order_id,
	                        "remark" =>"订单取消余额退回",
	                        "status" =>1,//有效
	                        'create_user' => "whaleyinfo.order DealerBiz.submitDealerOrder",
	                        'create_date' => date ( "y-m-d H:i:s", time () )
	                    );
	                    M('dealer_cashback_amount')->add($dealer_cashback_amount);
	                }
                }
                //endregion ============= 2、变更返现余额 End =============
            }

			redirect(C('AdminConfig.info_page').'?type=202&is_show_button=2&msg=成功,'."订单已取消！");
			return;
		}
			
	}
	
	/**
	 * Description: 返利计提EXCEL导出
	 * @version 2016年9月2日 下午2:56:01 
	 * @author lin.yujiao@whaley.cn
	 */
	public function rebateAccruedExcel(){
		 
		Vendor('phpExcel.PHPExcel');
		$objPHPExcel = OrderBiz::rebateAccruedExcel();
		 
		//输出到浏览器
		$objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
	
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
		header("Content-Type:application/force-download");
		header("Content-Type:application/vnd.ms-execl");
		header("Content-Type:application/octet-stream");
		header("Content-Type:application/download");
		header('Content-Disposition:attachment;filename="resume.xls"');
		header("Content-Transfer-Encoding:binary");
		$objWriter->save('php://output');
	}
}